<?php

namespace Customer;

use Bank\Bank;
use Products\Deposit;
use Products\Loan;
use exceptions\BaseException;

class Customer
{
	
	private $name;
	private $address;
	private $cash;
	private $monthSalary;
	public $deposits = array();
	public $loans = array();
   public $cards = array();
	
	public function __construct ($name, $address, $cash, $monthSalary)
	{
		if(strcspn($name, '01234567890+_)(*&^%$#@!`~-=][{}\'|\\",<.>/?') != strlen($name)){
			throw new BaseException("Invalid characters used in name!", BaseException::CODE_6001);
		}else{
			$this->name = $name;
		}
		
		$this->address = $address;
		
		if(!is_numeric($cash) || $cash < 0){
			throw new BaseException ("Cash should be 0 or a positive number!", BaseException::CODE_6002);
		}else{
			$this->cash = $cash;
		}
		
		if(!is_numeric($monthSalary) || $monthSalary < 0){
			throw new BaseException ("Month salary should be 0 or a positive number!", BaseException::CODE_6003);
		}else{
		$this->monthSalary = $monthSalary;
		}
		
	}
	
	public function getName()
	{
		return $this->name;
	}
	
	public function getMonthSalary()
	{
		return $this->monthSalary;
	}
	public function getCash()
	{
		return $this->cash;
	}
	
	public function openDeposit(Bank $bank, Deposit $deposit, $amount)
	{
		if($amount > $this->getCash())
		{
			throw new BaseException("Not enough cash!", BaseException::CODE_6004);
		}else {
			$deposit->setAmount($amount);
			$this->deposits[] = $deposit;
			$bank->addDeposit($deposit);
			$this->cash = $this->cash - $amount;
			echo "<p>".$this->name." made a successful ".$deposit->getName()." deposit for the amount of ".$amount." BGN.</p>";
		}
	}
	
	
	
	public function payInstalment(Loan $loan)
	{
		foreach ($this->loans as $aLoan)
		{
			if ($aLoan == $loan)
			{
				if($this->cash > $aLoan->getMonthlyPayment()){
					$aLoan->reduceAmount();
					$this->cash = $this->cash - $aLoan->getMonthlyPayment();
					echo "<p>".$this->name." paid an installment for the amount of ".$loan->getMonthlyPayment()." BGN</p>";
				}else{
					throw new BaseException("Not enough cash!", BaseException::CODE_6004);
				}
				
			}
		}
	}
	
	public function addLoan(Loan $loan)
	{
		
		$this->loans[] = $loan;
		$this->cash = $this->cash + $loan->getAmount();
		echo "<p>".$this->name." took successfully a ".$loan->getName(). " loan for the amount of ".$loan->getAmount()." BGN for a period of ". $loan->getPeriod()." months</p>";
	}
	
	public function showInfo()
	{
		echo "<p>".$this->name." is living on ".$this->address.".</p>
				<p>He/she is having ".$this->cash." BGN cash.</p>
				<p> His/her month salary is".$this->monthSalary." BGN.</p>";
		
		echo "<p><b>".$this->name." deposits and loans are: </b></p>";
		foreach($this->deposits as $deposit)
		{
			$deposit->showInfo();
		}
		foreach($this->loans as $loan)
		{
			$loan->showInfo();
	}
	
}
}


?>